//
//  TPRecomendViewController.m
//  TravelProject
//
//  Created by lanou3g on 15/11/23.
//  Copyright © 2015年 韩婷婷. All rights reserved.
//

#import "TPRecomendViewController.h"
#import "SDCycleScrollView.h"
#import "TPCheckAllCell.h"
#import "DestinationReusable.h"
#import "TPMaxPictureCell.h"
#import "TPMinPictureCell.h"
#import "TPPriceCell.h"
#import "TravelCell.h"
#import "HT_DataDownloadTools.h"
#import "RecomendDiscountModel.h"
#import "RecomendSliderModel.h"
#import "RecomendTravelModel.h"
#import "RecomendSubjectModel.h"
#import "UIImageView+WebCache.h"
#import "WebController.h"
#import "TPStationDetailController.h"
#import "TPPriceDetialController.h"

@interface TPRecomendViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
//轮播图
@property (weak, nonatomic) IBOutlet UIView *cycleScrollView;
//第一个collectionView
@property (weak, nonatomic) IBOutlet UICollectionView *nextCollectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *nextLayout;
//第二个collectionView
@property (weak, nonatomic) IBOutlet UICollectionView *specialCollectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *specialLayout;
//tableView
@property (weak, nonatomic) IBOutlet UITableView *tableView;
//轮播图数组
@property (nonatomic,strong) NSMutableArray *slideArray;
//下一站数组
@property (nonatomic,strong) NSMutableArray *subjectArray;
//特价折扣数组
@property (nonatomic,strong) NSMutableArray *discountArray;
//tableView数组
@property (nonatomic,strong) NSMutableArray *tableArray;
@property (nonatomic,assign) NSInteger page;
//下拉刷新
@property (nonatomic,strong) UIRefreshControl *control;

@end

@implementation TPRecomendViewController
+(instancetype)shareRecomendVC{
    static   TPRecomendViewController *recomendVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        recomendVC = [mainStoryBoard instantiateViewControllerWithIdentifier:@"recomend"];
    });
    return recomendVC;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //集成下拉刷新控件
    [self setupRefresh];
    
    
    
    
    
    
    // Do any additional setup after loading the view from its nib.
}
//集成下拉刷新控件
- (void)setupRefresh{
    _control = [[UIRefreshControl alloc]init];
    [_control addTarget: self  action:@selector(refreshStateChange:) forControlEvents:UIControlEventValueChanged];
    [self.scrollView addSubview:_control];
    [_control beginRefreshing];
    [self refreshStateChange:_control];
}
//进入刷新状态
- (void)refreshStateChange:(UIRefreshControl *)control{
    //加载下一站collectionView
    [self setupNextCollectionView];
    //加载特价折扣collectionView
    [self setupSpecialCollectionView];
    //加载tableView
    [self setupTableView];
    //请求上面部分数据
    [self requestData];
    //请求tableview数据
    self.page = 1;
    self.tableArray = [NSMutableArray array];
    for (int i = 0; i < 4; i++) {
        [self requestTableViewData];
        self.page++;
    }
    
    
}
//请求tableview数据
- (void)requestTableViewData{
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval =[date timeIntervalSince1970];
    [HT_DataDownloadTools downloadDataWithURL:[NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=865308021990677&track_app_version=6.8.2&track_app_channel=hicloud&track_device_info=hwH30-T00&track_os=Android4.2.2&app_installtime=%.0f&lat=40.029847&lon=116.343503&type=index&page=%ld&count=10",timeInterval * 1000,self.page] andMethod:@"get" andBody:nil andBlock:^(NSData *data) {
        [self solveTableData:data];
        [self.tableView reloadData];
    }];
}
- (void)solveTableData:(NSData *)data{
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSArray *array = dictionary[@"data"];
    for (NSDictionary *dic in array) {
        RecomendTravelModel *tm = [[RecomendTravelModel alloc]init];
        [tm setValuesForKeysWithDictionary:dic];
        [self.tableArray addObject:tm];
    }
}
//请求上面部分数据网络
- (void)requestData{
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval =[date timeIntervalSince1970];
    [HT_DataDownloadTools downloadDataWithURL:[NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/entry?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=865308021990677&track_app_version=6.8.2&track_app_channel=hicloud&track_device_info=hwH30-T00&track_os=Android4.2.2&app_installtime=%.0f&lat=40.029847&lon=116.343503&channel=hicloud",timeInterval * 1000] andMethod:@"get" andBody:nil andBlock:^(NSData *data) {
        [self solveData:data];
        //加载轮播图
        [self setupCycleScrollView];
        [self.nextCollectionView reloadData];
        [self.specialCollectionView reloadData];
        [_control endRefreshing];
    }];
}
//数据解析
- (void)solveData:(NSData *)data{
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSDictionary *diction = dictionary[@"data"];
    //轮播图数据解析
    self.slideArray = [NSMutableArray array];
    NSArray *array1 = diction[@"slide"];
    for (NSDictionary *d in array1) {
        RecomendSliderModel *s = [[RecomendSliderModel alloc]init];
        [s setValuesForKeysWithDictionary:d];
        [self.slideArray  addObject:s];
    }
    //第一个collectionView数据解析
    self.subjectArray = [NSMutableArray array];
    NSArray *array2 = diction[@"subject"];
    for (NSDictionary *d in array2) {
        RecomendSubjectModel *sm = [[RecomendSubjectModel alloc]init];
        [sm setValuesForKeysWithDictionary:d];
        [self.subjectArray addObject:sm];
    }
    //第二个collection的主题解析
    self.discountArray = [NSMutableArray array];
    NSArray *array4 = diction[@"discount_subject"];
    NSDictionary *d = array4[0];
    RecomendSliderModel *sm = [[RecomendSliderModel alloc]init];
    [sm setValuesForKeysWithDictionary:d];
    [self.discountArray addObject:sm];
    //第二个collectionView数据解析
    NSArray *array3 = diction[@"discount"];
    for (NSDictionary *d in array3) {
        RecomendDiscountModel *sm = [[RecomendDiscountModel alloc]init];
        [sm setValuesForKeysWithDictionary:d];
        [self.discountArray addObject:sm];
    }
}
//加载tableView
- (void)setupTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    UINib *nib = [UINib nibWithNibName:@"TravelCell" bundle:[NSBundle mainBundle]];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"travel"];
}
//加载特价折扣collectionView
- (void)setupSpecialCollectionView{
    _specialLayout.itemSize = CGSizeMake((CGRectGetWidth([UIScreen mainScreen].bounds)-100)/3, 300);
    _specialLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.specialCollectionView.delegate = self;
    self.specialCollectionView.dataSource = self;
    UINib *nib1 = [UINib nibWithNibName:@"TPMaxPictureCell" bundle:[NSBundle mainBundle]];
    [self.specialCollectionView registerNib:nib1 forCellWithReuseIdentifier:@"special_max"];
    UINib *nib2 = [UINib nibWithNibName:@"TPPriceCell" bundle:[NSBundle mainBundle]];
    [self.specialCollectionView registerNib:nib2 forCellWithReuseIdentifier:@"special_price"];
    UINib *nib3 = [UINib nibWithNibName:@"TPCheckAllCell" bundle:[NSBundle mainBundle]];
    [self.specialCollectionView registerNib:nib3 forCellWithReuseIdentifier:@"special_check"];
    UINib *nib4 = [UINib nibWithNibName:@"DestinationReusable" bundle:[NSBundle mainBundle]];
    [self.specialCollectionView registerNib:nib4 forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"special_header"];
}
//加载下一站collectionView
- (void)setupNextCollectionView{
    _nextLayout.itemSize = CGSizeMake((CGRectGetWidth([UIScreen mainScreen].bounds)-100)/3, 300);
    _nextLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.nextCollectionView.delegate = self;
    self.nextCollectionView.dataSource = self;
    UINib *nib1 = [UINib nibWithNibName:@"TPMaxPictureCell" bundle:[NSBundle mainBundle]];
    [self.nextCollectionView registerNib:nib1 forCellWithReuseIdentifier:@"next_max"];
    UINib *nib2 = [UINib nibWithNibName:@"TPMinPictureCell" bundle:[NSBundle mainBundle]];
    [self.nextCollectionView registerNib:nib2 forCellWithReuseIdentifier:@"next_min"];
    UINib *nib3 = [UINib nibWithNibName:@"TPCheckAllCell" bundle:[NSBundle mainBundle]];
    [self.nextCollectionView registerNib:nib3 forCellWithReuseIdentifier:@"next_check"];
    UINib *nib4 = [UINib nibWithNibName:@"DestinationReusable" bundle:[NSBundle mainBundle]];
    [self.nextCollectionView registerNib:nib4 forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"next_header"];
}
//添加轮播图
-(void)setupCycleScrollView{
    // self.cycleScrollView.backgroundColor = [UIColor whiteColor];
    NSMutableArray *mArray = [NSMutableArray array];
    for (RecomendSliderModel *m in self.slideArray) {
        [mArray addObject:m.photo];
    }
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250)imageURLStringsGroup:mArray];
    cycleScrollView.infiniteLoop = YES;
    cycleScrollView.delegate = self;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    cycleScrollView.autoScrollTimeInterval = 2.5;
    [self.cycleScrollView addSubview:cycleScrollView];
}
//轮播图代理方法
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
  RecomendSliderModel *slider = self.slideArray[index];
    WebController *wc = [[WebController alloc]init];
    wc.urlString = slider.url;
    [self.navigationController pushViewController:wc animated:YES];
}
#pragma mark --- 设置tableView
//row个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    self.scrollView.contentSize =CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetMaxY(self.specialCollectionView.frame)+80 * self.tableArray.count + 40);
    return self.tableArray.count;
}
//几个section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
//设置Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TravelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"travel" forIndexPath:indexPath];
    RecomendTravelModel *m = self.tableArray[indexPath.row];
    cell.model = m;
    return cell;
}
//设置header
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"看热门游记";
}
//设置每个row的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RecomendTravelModel *m = self.tableArray[indexPath.row];
    WebController *wc = [[WebController alloc]init];
    wc.urlString =[NSString stringWithFormat:@"http://appview.qyer.com/bbs/thread-%ld-1.html?source=app&client_id=qyer_android&track_user_id=&track_deviceid=865308021990677&track_app_version=6.8.2",m.ID];
    [self.navigationController pushViewController:wc animated:YES];
}
#pragma  mark --- 设置collectionView
//Item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == _nextCollectionView) {
        return 4;
    }else{
        return 6;
    }
}
//分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
//设置Item(Cell)
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _nextCollectionView) {
        if (indexPath.row == 0) {
            TPMaxPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"next_max" forIndexPath:indexPath];
            RecomendSubjectModel *m = self.subjectArray[0];
            [cell.imagePicture sd_setImageWithURL:[NSURL URLWithString:m.photo]];
            return cell;
        }else if(indexPath.row == 3){
            TPCheckAllCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"next_check" forIndexPath:indexPath];
            return cell;
        }else{
            TPMinPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"next_min" forIndexPath:indexPath];
            RecomendSubjectModel *m = self.subjectArray[indexPath.row];
            [cell.imagePicture sd_setImageWithURL:[NSURL URLWithString:m.photo]];
            return cell;
        }
        return nil;
        
    }else{
        if (indexPath.row == 0) {
            TPMaxPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"special_max" forIndexPath:indexPath];
            RecomendDiscountModel *d = self.discountArray[indexPath.row];
            [cell.imagePicture sd_setImageWithURL:[NSURL URLWithString:d.photo]];
            return cell;
        }else if(indexPath.row == 5){
            TPCheckAllCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"special_check" forIndexPath:indexPath];
            return cell;
        }else{
            TPPriceCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"special_price" forIndexPath:indexPath];
            RecomendDiscountModel *d = self.discountArray[indexPath.row];
            cell.recomendModel = d;
            return cell;
        }
    }
}
//选中某个Item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _nextCollectionView) {
        if (indexPath.row == 0) {
            RecomendSubjectModel *m = self.subjectArray[0];
            WebController *wc = [[WebController alloc]init];
            wc.urlString = m.url;
          [self.navigationController pushViewController:wc animated:YES];
        }else if(indexPath.row == 3){
            TPStationDetailController *sta = [TPStationDetailController shareStationVC];
            [self.navigationController pushViewController:sta animated:YES];
            
        }else{
            RecomendSubjectModel *m = self.subjectArray[indexPath.row];
            WebController *wc = [[WebController alloc]init];
            wc.urlString = m.url;
            [self.navigationController pushViewController:wc animated:YES];
        }
        
    }else{
        if (indexPath.row == 0) {
            RecomendSubjectModel *m = self.subjectArray.lastObject;
            WebController *wc = [[WebController alloc]init];
            wc.urlString =m.url;
          [self.navigationController pushViewController:wc animated:YES];
        }else if(indexPath.row == 5){
            TPPriceDetialController *price = [TPPriceDetialController sharePriceVC];
            [self.navigationController pushViewController:price animated:YES];
        }else{
            RecomendDiscountModel *m = self.discountArray[indexPath.row];
            WebController *wc = [[WebController alloc]init];
            wc.urlString =[NSString stringWithFormat:@"http://m.qyer.com/z/deal/%ld/?source=app&client_id=qyer_android&track_app_version=6.8.2&track_deviceid=865308021990677",m.ID];
           [self.navigationController pushViewController:wc animated:YES];
        }
    }
}
//设置Layout大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _nextCollectionView) {
        if (indexPath.row == 0) {
            return  CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds)-20, 150);
        }else if(indexPath.row == 3){
            return  CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds)-20, 30);
        }else{
            return  CGSizeMake((CGRectGetWidth([UIScreen mainScreen].bounds)-30)/2, 100);
        }
    }else{
        if (indexPath.row == 0) {
            return  CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds)-20, 150);
        }else if(indexPath.row == 5){
            return  CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds)-20, 30);
        }else{
            return  CGSizeMake((CGRectGetWidth([UIScreen mainScreen].bounds)-30)/2, 170);
        }
    }
}
//设置header
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _nextCollectionView) {
        DestinationReusable *cell = (DestinationReusable *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"next_header" forIndexPath:indexPath];
        cell.label.text = @"发现下一站";
        return cell;
    }else{
        DestinationReusable *cell = (DestinationReusable *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"special_header" forIndexPath:indexPath];
        cell.label.text = @"特价折扣";
        return cell;
    }
}




























- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
